/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.constant.KwConstant;
import me.zhengjie.domain.KwExamStudent;
import me.zhengjie.exception.ParameterException;
import me.zhengjie.kwService.ExamStudentService;
import me.zhengjie.pojo.entity.ExamStudent;
import me.zhengjie.pojo.export.ExamStudentExport;
import me.zhengjie.service.KwExamStudentService;
import me.zhengjie.service.dto.KwExamStudentQueryCriteria;
import me.zhengjie.util.BaseResponse;
import me.zhengjie.util.KwUtils;
import me.zhengjie.util.ruoyiexcel.ExcelUtil;
import me.zhengjie.util.ruoyiexcel.FileTypeUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author LongYang
 * @website https://el-admin.vip
 * @date 2021-06-28
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "考场考生安排安排表前端控制器管理")
@RequestMapping("/api/kwExamStudent")
public class KwExamStudentController {

    private final KwExamStudentService kwExamStudentService;
    private final ExamStudentService examStudentService;
    private final KwUtils kwUtils;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('kwExamStudent:list')")
    public void download(HttpServletResponse response, KwExamStudentQueryCriteria criteria) throws IOException {
        String identity = kwUtils.identity();
        if (Objects.equals(identity, KwConstant.DEPT)) throw new ParameterException("无权操作");
        kwExamStudentService.download(kwExamStudentService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询考场考生安排安排表前端控制器")
    @ApiOperation("查询考场考生安排安排表前端控制器")
    @PreAuthorize("@el.check('kwExamStudent:list')")
    public ResponseEntity<Object> query(KwExamStudentQueryCriteria criteria, Pageable pageable) {
        Integer examId = criteria.getExamId();
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            return null;
        }
        return new ResponseEntity<>(kwExamStudentService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增考场考生安排安排表前端控制器")
    @ApiOperation("新增考场考生安排安排表前端控制器")
    @PreAuthorize("@el.check('kwExamStudent:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody KwExamStudent resources) {
        Integer examId = resources.getExamId();
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            throw new ParameterException("无权操作");
        }
        return new ResponseEntity<>(kwExamStudentService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改考场考生安排安排表前端控制器")
    @ApiOperation("修改考场考生安排安排表前端控制器")
    @PreAuthorize("@el.check('kwExamStudent:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody KwExamStudent resources) {
        Integer examId = resources.getExamId();
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            throw new ParameterException("无权操作");
        }
        kwExamStudentService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除考场考生安排安排表前端控制器")
    @ApiOperation("删除考场考生安排安排表前端控制器")
    @PreAuthorize("@el.check('kwExamStudent:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Integer[] ids) {
        String identity = kwUtils.identity();
        if (Objects.equals(identity, KwConstant.DEPT)) throw new ParameterException("无权操作");
        kwExamStudentService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /*--------------------------------------分界线-----------------------------------------*/

    @ApiOperation("考场考生安排信息导出")
    @PostMapping("/ruoyiExport")
    @PreAuthorize("@el.check('kwExamStudent:ruoyiExport')")
    public BaseResponse export(HttpServletResponse response, @RequestBody List<ExamStudent> examStudents) throws Exception {
        List<Integer> examIds = examStudents.stream().map(ExamStudent::getExamId).collect(Collectors.toList());
        boolean permission = kwUtils.hasOtherPermission(examIds);
        if (!permission) {
            throw new ParameterException("无权操作");
        }
        String identity = kwUtils.identity();
        if (Objects.equals(identity, KwConstant.DEPT)) throw new ParameterException("无权操作");
        try {
            return examStudentService.export(response, examStudents);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.failed("导出失败：" + e.getMessage());
        }
    }

    @ApiOperation("考场考生安排信息导入")
    @PostMapping("/ruoyiImport")
    @PreAuthorize("@el.check('kwExamStudent:ruoyiImport')")
    public BaseResponse ruoYiImport(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "examId") Integer examId) {
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            throw new ParameterException("无权操作");
        }
        String identity = kwUtils.identity();
        if (Objects.equals(identity, KwConstant.DEPT)) throw new ParameterException("无权操作");
        if (file.isEmpty()) {
            return BaseResponse.failed("导入了空文件");
        }
        String suffix = FileTypeUtils.getFileType(file.getResource().getFilename());
        System.out.println("后缀名:" + suffix);
        if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) {
            return BaseResponse.failed("请导入xls，xlsx文件");
        }
        ExcelUtil<ExamStudentExport> util = new ExcelUtil<>(ExamStudentExport.class);
        try {
            List<ExamStudentExport> examStudentExports = util.importExcel(file.getInputStream());
            if (examStudentExports.isEmpty()) {
                return BaseResponse.failed("导入文件为空");
            }
            examStudentService.saveImportList(examStudentExports, examId);
            return BaseResponse.ok("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.failed("导入失败：" + e.getMessage());
        }
    }

    @ApiOperation("考场考生安排信息模板下载")
    @GetMapping("/import-ExamStudent")
    @PreAuthorize("@el.check('kwExamStudent:template')")
    public void downloadKwExamTemplate(HttpServletResponse response) throws Exception {
        ExcelUtil<ExamStudentExport> excelUtil = new ExcelUtil<>(ExamStudentExport.class);
        /* excelUtil.importTemplateExcel("考场考生安排信息");*/
        excelUtil.importTemplateExcel(response, "考场考生安排信息");
    }


    /*@ApiModelProperty("考场考生成绩模板下载")
    @GetMapping("/download-examination-result-template")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        ExcelUtil<ExaminationResultExport> excelUtil = new ExcelUtil<>(ExaminationResultExport.class);
        excelUtil.importTemplateExcel(response, "考场考生成绩");
    }

    @ApiModelProperty("考场考生成绩导出")
    @PostMapping("/export-examination-result")
    public BaseResponse exportExaminationResult(HttpServletResponse response, @RequestBody List<ExamStudent> examStudents) {
        try {
            return examStudentService.exportExaminationResult(response, examStudents);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.failed("导出失败：" + e.getMessage());
        }
    }

    @ApiModelProperty("考场考生成绩导入")
    @PostMapping("/import-examination-result")
    public BaseResponse importExaminationResult(@RequestParam(value = "file") MultipartFile file) {
        if (file.isEmpty()) {
            return BaseResponse.failed("导入了空文件");
        }
        String suffix = FileTypeUtils.getFileType(file.getResource().getFilename());
        if (!"xls".equals(suffix) && !"xlsx".equals(suffix)){
            return BaseResponse.failed("请导入xls，xlsx文件");
        }
        ExcelUtil<ExaminationResultExport> excelUtil = new ExcelUtil<>(ExaminationResultExport.class);
        try {
            List<ExaminationResultExport> resultExportList = excelUtil.importExcel(file.getInputStream());
            if(resultExportList.isEmpty()){
                return BaseResponse.failed("导入文件为空");
            }
            examStudentService.saveImportExaminationResult(resultExportList);
            return BaseResponse.ok("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.failed("导入失败："+e.getMessage());
        }
    }*/


}